package com.ruoyi.system.netty;

import com.ruoyi.common.core.domain.entity.SysUser;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chiecal
 * @date 2021年05月16日 10:05
 */
@Slf4j
public class NettyTcpServer {
    private final int port;
    private final CustomHandler customHandler;


    // 保存设备ID与channel的映射，方便下发指令
    public static final ConcurrentHashMap<String, Channel> deviceChannelMap = new ConcurrentHashMap<>();


    public static final ConcurrentHashMap<String, SysUser> deviceUserChannelMap = new ConcurrentHashMap<>();


    public static final ConcurrentHashMap<String, String> userNameDeviceChannelMap = new ConcurrentHashMap<>();

    public NettyTcpServer(int port, CustomHandler customHandler) {
        this.port = port;
        this.customHandler = customHandler;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new HelloNettyServerInitializer(customHandler));
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}
